import { getToken } from '@/utils/auth'
import axios from 'axios'
import Qs from 'qs'

// request interceptor
axios.interceptors.request.use(config => {
  config.headers['accessToken'] = getToken()
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
axios.interceptors.response.use(
  response => response.data,
  error => {
    switch (error.response.status) {
      case 400:
        error.message = '请求错误'
        break
      case 401:
        error.message = '未授权，请登录'
        break
      case 403:
        error.message = '拒绝访问'
        break
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`
        break
      case 408:
        error.message = '请求超时'
        break
      case 500:
        error.message = '服务器内部错误'
        break
      case 501:
        error.message = '服务未实现'
        break
      case 502:
        error.message = '网关错误'
        break
      case 503:
        error.message = '服务不可用'
        break
      case 504:
        error.message = '网关超时'
        break
      case 505:
        error.message = 'HTTP版本不受支持'
        break
      case 900:
        error.message = error.response.data.message
        break
      default:
        error.message = ''
        break
    }
    return Promise.reject(error)
  })

export { axios }
export default (url = '', data = {}, type = 'POST', dataType) => {
  let option = {
    baseURL: process.env.NODE_ENV === 'development' ? '' : window.APIPATH,
    timeout: 60 * 2 * 1000,
    method: type,
    url: url
  }
  console.log('Content-Type:' + axios.defaults.headers['Content-Type'])
  if (dataType === 'json') {
    axios.defaults.headers['Content-Type'] = 'application/json'
  } else {
    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  if (/^post|put|patch$/i.test(type)) {
    if (dataType !== 'json') {
      option.data = Qs.stringify(data)
    } else {
      option.data = data
    }
  } else {
    option.params = data
  }
  return axios(option)
}
